$(function() {
	// load tree func
	var loadTree = function() {
		$('.menu-tree').tree({
			click : function() {
				var nodeData = $.suredy.tree.data(this);
				$('#selected-info').html(nodeData.text);
				// unabled top node delete click
				if (nodeData._tree_id === $.suredy.tree.data($('.menu-tree .node:first-child'))._tree_id) {
					$('#edit').addClass('hidden');
					$('#remove').addClass('hidden');
				} else {
					$('#edit').removeClass('hidden');
					$('#remove').removeClass('hidden');
				}
			}
		});
	};
	
	// load tree
	loadTree();

	// new menu btn click
	$('#create').on('click', function() {		
		$.suredy.showModal({
			size : 'lg',
			icon : 'icon-plus',
			title : '创建菜单项',
			showFoot : false,
			uri : 'menu-create.do'
		});
	
	});
	
	// edit menu btn click
	$('#edit').on('click', function() {	
		var selectedTreeNode = $.suredy.tree.selected($('.menu-tree'));

		if (selectedTreeNode.length <= 0) {
			alert('请选择需要修改的菜单节点！');
			return;
		}
		// data on selected node
		var nodeData = $.suredy.tree.data(selectedTreeNode);

		if (!nodeData.data) {
			alert('Can not find tree node info.');
			return;
		}
		var menuId = nodeData.data.id
		$.suredy.showModal({
			size : 'lg',
			icon : 'icon-edit',
			title : '修改菜单项',
			showFoot : false,
			uri : 'menu-edit.do?menuId=' + menuId
		});
	
	});

	// remove btn click
	$('#remove').on('click', function() {
		// get selected node
		var selectedTreeNode = $.suredy.tree.selected($('.menu-tree'));

		if (selectedTreeNode.length <= 0) {
			alert('请选择需要删除的菜单节点！');
			return;
		}

		// data on selected node
		var nodeData = $.suredy.tree.data(selectedTreeNode);

		if (!nodeData.data) {
			alert('Can not find tree node info.');
			return;
		}

		var msg = '是否确认删除【' + nodeData.data.name + '】？\n\n\
					提示：\n\
					该操作将会删除菜单下的所有子节点！\n\
					请谨慎操作！';

		if (!window.confirm(msg))
			return;

		$.ajax({
			url : 'menu-delete.do',
			type : 'POST',
			data : {
				menuId : nodeData.data.id
			},
			success : function(msg) {
				if (!msg) {
					alert('Unknown exception!');
				} else if (!msg.success) {
					alert("删除菜单节点失败！\n\n" + msg.msg);
				} else {
					alert("删除菜单节点成功！");

					$('#selected-info').html('请选择菜单节点');

					loadTree();

					$('.delete-menu').addClass('hidden');
				}
			},
			error : function(a, b, c) {
				alert('Server error! ' + b);
			}
		});
	});

});